package com.ruoyi.mqtt.config;

import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

@Component
public class MqttClientConnect {

    MqttClient mqttClient;
    // 客户端与服务器之间的连接意外中断，服务器将发布客户端的“遗嘱”消息
    private static final byte[] WILL_DATA;
    static {
        WILL_DATA = "offline".getBytes();
    }

    @Value("${mqtt.client.username}")
    private String username;

    @Value("${mqtt.client.password}")
    private String password;

    @Value("${mqtt.client.brokerURIs}")
    private String brokeURIs;

    @Value("${mqtt.client.keepAliveInterval}")
    private Integer keepAliveInterval;

    @Value("${mqtt.client.connectionTimeout}")
    private Integer connectionTimeout;

    @Value("${mqtt.client.clientId}")
    private String clientId;

    @Value("${mqtt.client.defaultQos}")
    private Integer defaultQos;

    /**
     * MQTT连接参数设置
     */
    @PostConstruct //在对象创建之后立马执行
    public void initMqttClient() throws MqttException {
        this.mqttClient = new MqttClient(
                brokeURIs,
                clientId, new MemoryPersistence());
        MqttConnectOptions options = new MqttConnectOptions();
        options.setUserName(username);
        options.setPassword(password.toCharArray());
        options.setConnectionTimeout(connectionTimeout);///默认：30
        options.setAutomaticReconnect(true);//默认：false
        options.setCleanSession(false);//默认：true
        options.setKeepAliveInterval(keepAliveInterval);//默认：60
        options.setWill("willTopic", WILL_DATA, 2, false);
        this.mqttClient.connect(options);
    }

    /**
     * 关闭MQTT连接
     */
    public void close() throws MqttException {
        mqttClient.disconnect();
        mqttClient.close();
    }

    /**
     * 向某个主题发布消息 默认qos：1
     *
     * @param topic:发布的主题
     * @param msg：发布的消息
     */
    public void publish(String topic, String msg) throws MqttException {
        MqttMessage mqttMessage = new MqttMessage();
        //mqttMessage.setQos(2);
        mqttMessage.setPayload(msg.getBytes());
        MqttTopic mqttTopic = mqttClient.getTopic(topic);
        MqttDeliveryToken token = mqttTopic.publish(mqttMessage);
        token.waitForCompletion();
    }

    /**
     * 向某个主题发布消息
     * @param topic: 发布的主题
     * @param msg:   发布的消息
     * @param qos:   消息质量    Qos：0、1、2
     *           0   发送消息 最多一次，消费方 可能丢失
     *           1   发送消息 最少一次，消费方 可能重复消费
     *           2   发送消息 一次且仅有一次，消费方 收到且只收到一次
     */
    public void publish(String topic, String msg, int qos) throws MqttException {
        MqttMessage mqttMessage = new MqttMessage();
        mqttMessage.setQos(qos);
        mqttMessage.setPayload(msg.getBytes());
        MqttTopic mqttTopic = mqttClient.getTopic(topic);
        MqttDeliveryToken token = mqttTopic.publish(mqttMessage);
        token.waitForCompletion();
    }

    public void setCallback(MqttCallback mqttCallback) throws MqttException {
        mqttClient.setCallback(mqttCallback);
    }
    /**
     * 订阅某一个主题 ，此方法默认的的Qos等级为：1
     *
     * @param topic 主题
     */
    public void subscribe(String topic) throws MqttException {
        mqttClient.subscribe(topic);
    }

    /**
     * 订阅某一个主题，可携带Qos
     *
     * @param topic 所要订阅的主题
     * @param qos   消息质量：0、1、2
     */
    public void subscribe(String topic, int qos) throws MqttException {
        mqttClient.subscribe(topic, qos);
    }

    /**
     * main函数自己测试用
     */
    public static void main(String[] args) throws MqttException {

    }
}
